package com.example.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.common.constant.CartServerConstant;
import com.example.common.utils.R;
import com.example.gulimall.cart.feign.ProductFeignService;
import com.example.gulimall.cart.interceptor.CartInterceptor;
import com.example.gulimall.cart.service.CartService;
import com.example.gulimall.cart.to.UserInfoTo;
import com.example.gulimall.cart.vo.CartItemVo;
import com.example.gulimall.cart.vo.CartVo;
import com.example.gulimall.cart.vo.SkuInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    ProductFeignService productFeignService;
    final static String CART_PREFIX="gulimall:cart:";
    @Override
    public CartItemVo addCartItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartItemOps = getCartItemOps();
        //判断购物车是否有这个物品
        String o = (String) cartItemOps.get(skuId.toString());
        //如果有只需要改变商品数量
        if(StringUtils.isNotEmpty(o)){
            CartItemVo cartItemVo = JSON.parseObject(o, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount()+num);
            String s = JSON.toJSONString(cartItemVo);
            cartItemOps.put(skuId.toString(),s);
            return cartItemVo;
        }
        //如果没有需要查找后放入
        else{
            CartItemVo cartItemVo = new CartItemVo();
            //获取skuinfo的信息
            CompletableFuture<Void> getSkuInfo=CompletableFuture.runAsync(()->{
                R Info = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = Info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItemVo.setCheck(true);
                cartItemVo.setCount(num);
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setSkuId(skuId);
                cartItemVo.setTitle(skuInfo.getSkuTitle());
            },executor);
            //获取sku的销售属性信息
            CompletableFuture<Void> getSkuSalesInfo=CompletableFuture.runAsync(()->{
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            },executor);
            try {
                //allOf等待所有异步任务完成后再进行存储
                CompletableFuture.allOf(getSkuInfo, getSkuSalesInfo).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            String s = JSON.toJSONString(cartItemVo);
            cartItemOps.put(skuId.toString(),s);
            return cartItemVo;
        }
    }
    @Override
    public CartItemVo getCartItem(Long skuId) {
        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartItemOps();

        String redisValue = (String) cartOps.get(skuId.toString());

        CartItemVo cartItemVo = JSON.parseObject(redisValue, CartItemVo.class);

        return cartItemVo;
    }

    @Override
    public CartVo getCart() {
        CartVo cartVo=new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        List<CartItemVo>  cartItemVos=getCartItem(CART_PREFIX+userInfoTo.getUserKey());
        //如果是未登录用户显示离线购物车
        if(StringUtils.isEmpty(userInfoTo.getUserId().toString())){
            cartVo.setItems(cartItemVos);
        }
        //是已登录用于需要展示离线购物车和用户购物车的信息，同时更新redis储存的数据
        else{
            List<CartItemVo> cartItems = getCartItem(CART_PREFIX
                    + userInfoTo.getUserId().toString());
            if(cartItems!=null&&cartItems.size()>0){
                for (CartItemVo cartItemVo : cartItemVos) {
                    cartItems.add(cartItemVo);
                    addCartItem(cartItemVo.getSkuId(),cartItemVo.getCount());
                }
            }
            cartVo.setItems(cartItems);
            redisTemplate.delete(CART_PREFIX+userInfoTo.getUserKey());
        }
        return cartVo;
    }

    @Override
    public void checkCart(Integer isChecked, Long skuId) {
        BoundHashOperations<String, Object, Object> cartItemOps = getCartItemOps();
        String o = (String) cartItemOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(o, CartItemVo.class);
        cartItemVo.setCheck(isChecked==1);
        cartItemOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> ops = getCartItemOps();
        String cartJson = (String) ops.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(cartJson, CartItemVo.class);
        cartItemVo.setCount(num);
        ops.put(skuId.toString(),JSON.toJSONString(cartItemVo));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartItemOps = getCartItemOps();
        cartItemOps.delete(skuId.toString());
    }

    @Override
    public List<CartItemVo> getUserCartItems() {
        List<CartItemVo> cartItemVos=new ArrayList<>();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()==null){
            return null;
        }
        else{
            String key=CART_PREFIX+userInfoTo.getUserKey().toString();
            List<CartItemVo> cartItem = getCartItem(key);
            if(cartItem==null||cartItem.size()==0){
                return null;
            }else{
                cartItemVos = cartItem.stream().filter(CartItemVo::getCheck).map(item -> {
                    item.setPrice(productFeignService.getPrice(item.getSkuId()));
                    return item;
                }).collect(Collectors.toList());
                return cartItemVos;
            }
        }

    }

    /**
     * 获取购物车对应user的数据
     * @param key
     * @return
     */
    private List<CartItemVo> getCartItem(String key) {
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(key);
        List<Object> values = ops.values();
        if(values!=null&&values.size()>0){
            List<CartItemVo> collect = values.stream().map(item -> {
                return JSON.parseObject((String) item, CartItemVo.class);
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 获取在线用户或者离线用户的购物车队友的redis操作ops
     * @return
     */
    public BoundHashOperations<String, Object, Object> getCartItemOps(){
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()!=null){
            return redisTemplate.boundHashOps(CART_PREFIX+userInfoTo.getUserId().toString());
        }
        else{
            return redisTemplate.boundHashOps(CART_PREFIX+userInfoTo.getUserKey());

        }

    }
}
